<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布/订阅模式</title>
</head>
<body>
    <script>
        class EventEmitter{
            constructor() {
                this.subs = Object.create(null); // object.create创建对象性能比{}好
            }
            // 注册事件([事件名]，[方法])   $on('',()=>{})  $on('',()=>{})
            $on(eventType, handler) {
                this.subs[eventType] = this.subs[eventType] || [];
                this.subs[eventType].push(handler)
            }
            //  触发事件 $emit('')
            $emit(eventType) {
                if (this.subs[eventType]) {
                    this.subs[eventType].forEach(handler => {
                        handler();
                    });
                }
            }   
        }

        let em = new EventEmitter();
        em.$on('click',()=>{
            console.log(1111)
        })
        em.$emit('click')
    </script>
</body>
</html>